#!/bin/bash

## 编译镜像并远程服务器上load该镜像
##### build
if [ ! -n "$1" ];then
    echo "请输入需要部署的远程服务器ip"
    exit 1
fi


if [ ! -n "$2" ];then
    echo "请输入变更的服务名/deployment"
    exit 1
fi


echo "************** build start **************"

IMAGE_NAME=$(cat name)
VERSION=$(git symbolic-ref --short -q HEAD)
DATE=$(date "+%m%d")
## 判断当前日期是否已经有镜像
CURRENT_NUM=$(docker images | grep "${VERSION}-${DATE}" -c)
NUM=""
## 十位补0(正常情况不会一天打10个包)
if [ "${CURRENT_NUM}" -ne 0 ]; then
  COMMIT_ID_1=$(git rev-parse --short HEAD)
  TAG_1="${VERSION}-${DATE}.*-${COMMIT_ID_1}"
  GREP_OUTPUT="$(docker images | grep "${TAG_1}")"
  if [ -n "$GREP_OUTPUT" ] ; then
    echo "已有该镜像："
    echo "${GREP_OUTPUT}"
    exit 0
  fi
  NUM=$(("${CURRENT_NUM}"))
  NUM="0""${NUM}"
fi
COMMIT_ID=$(git rev-parse --short HEAD)
TAG="${VERSION}-${DATE}${NUM}-${COMMIT_ID}"
mvn clean package -Dmaven.test.skip=true docker:build -DimageName="${IMAGE_NAME}" -Dtag="${TAG}"
echo "镜像：${IMAGE_NAME}:${TAG}"

echo "************** build end **************"


# 本地保存的镜像文件地址
BASE_SAVE_PATH="/tmp"
# 本地保存的镜像文件名称
SAVE_IMAGE_NAME="${BASE_SAVE_PATH}/${TAG}.tar"

# 远程服务器ip
REMOTE_IP=$1

# 需要更改的服务名称 deployment名称
SERVICE_NAME=$2
# 镜像文件在远程服务器上的地址
REMOTE_SAVE_PATH="/tmp"
# 保存本地镜像文件
docker save -o ${SAVE_IMAGE_NAME} ${IMAGE_NAME}:${TAG}
echo "************** save image success **************"


## scp需要免密登录 ssh-copy-id -i ~/.ssh/id_rsa.pub  172.17.4.123
scp ${SAVE_IMAGE_NAME} ${REMOTE_IP}:${REMOTE_SAVE_PATH}

echo "************** scp to remote(${REMOTE_IP}:${REMOTE_SAVE_PATH}) success**************"


REPLACE_LINE='image: '${IMAGE_NAME}:${TAG}

# ssh 远程执行命令
# 1. load镜像
# 2. 更新镜像

ssh ${REMOTE_IP} "
    docker load -i ${REMOTE_SAVE_PATH}/${TAG}.tar;
    echo 'remote(${REMOTE_IP}) load image success: ${IMAGE_NAME}:${TAG}';
    kubectl set image deployment/${SERVICE_NAME}  ${SERVICE_NAME}=${IMAGE_NAME}:${TAG}
    "
